<template>
  <div class="analytics-page">
    <!-- 页面标题和过滤器 -->
    <div class="page-header">
      <div class="header-left">
        <h1>数据分析中心</h1>
        <p class="subtitle">系统运行和业务数据的详细分析</p>
      </div>
      <div class="header-right">
        <el-select
          v-model="timeRange"
          placeholder="选择时间范围"
          size="large"
          class="time-range-select"
        >
          <el-option
            v-for="item in timeRangeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" :icon="Refresh" @click="refreshData">
          刷新数据
        </el-button>
        <el-tooltip content="导出数据为Excel" placement="top">
          <el-button :icon="Download" @click="exportData" circle plain />
        </el-tooltip>
      </div>
    </div>

    <!-- 统计卡片行 -->
    <div class="stat-cards-row">
      <stat-card
        v-for="(card, index) in statCards"
        :key="index"
        :value="card.value"
        :label="card.label"
        :unit="card.unit"
        :icon="card.icon"
        :type="card.type"
        :trend="card.trend"
        :chart-data="card.chartData"
        :loading="loading"
        show-action
        @action="handleCardAction(card)"
      />
    </div>

    <!-- 主要趋势图表 -->
    <el-card class="main-chart-card" shadow="hover">
      <template #header>
        <div class="chart-card-header">
          <h3>系统性能趋势</h3>
          <div class="chart-controls">
            <el-radio-group v-model="selectedMetric" size="small">
              <el-radio-button
                v-for="metric in metrics"
                :key="metric.value"
                :label="metric.value"
              >
                {{ metric.label }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
      </template>

      <div v-if="loading" class="chart-loading-container">
        <el-skeleton animated :rows="6" />
      </div>
      <base-chart
        v-else
        :option="trendChartOption"
        height="400px"
        @click="handleChartClick"
      />
    </el-card>

    <!-- 数据分析卡片行 -->
    <div class="data-analysis-row">
      <!-- 用户分布卡片 -->
      <el-card class="analysis-card" shadow="hover">
        <template #header>
          <div class="chart-card-header">
            <h3>用户地域分布</h3>
            <el-select v-model="userDistType" size="small" style="width: 120px">
              <el-option label="省份" value="province" />
              <el-option label="城市" value="city" />
              <el-option label="终端类型" value="device" />
            </el-select>
          </div>
        </template>

        <div v-if="loading" class="chart-loading-container">
          <el-skeleton animated :rows="3" />
        </div>
        <base-chart
          v-else
          :option="userDistributionChartOption"
          height="300px"
        />
      </el-card>

      <!-- 转化漏斗卡片 -->
      <el-card class="analysis-card" shadow="hover">
        <template #header>
          <div class="chart-card-header">
            <h3>业务转化漏斗</h3>
            <el-tooltip content="访问-注册-激活-付费转化漏斗" placement="top">
              <el-icon class="info-icon"><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>

        <div v-if="loading" class="chart-loading-container">
          <el-skeleton animated :rows="3" />
        </div>
        <base-chart
          v-else
          :option="funnelChartOption"
          height="300px"
        />
      </el-card>
    </div>

    <!-- 详细数据表格 -->
    <el-card class="data-table-card" shadow="hover">
      <template #header>
        <div class="chart-card-header">
          <h3>详细指标数据</h3>
          <div class="table-controls">
            <el-input
              v-model="searchQuery"
              placeholder="搜索..."
              prefix-icon="Search"
              size="small"
              style="width: 200px; margin-right: 10px"
            />
            <el-select
              v-model="tableFilterType"
              size="small"
              style="width: 120px"
            >
              <el-option label="全部指标" value="all" />
              <el-option label="重点关注" value="important" />
              <el-option label="异常数据" value="anomaly" />
            </el-select>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="filteredTableData"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column
          prop="date"
          label="日期"
          width="120"
          sortable
        />
        <el-table-column
          prop="name"
          label="指标名称"
          width="160"
        />
        <el-table-column
          prop="value"
          label="数值"
          width="100"
          sortable
        >
          <template #default="scope">
            {{ formatNumberWithCommas(scope.row.value) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="ratio"
          label="环比"
          width="100"
          sortable
        >
          <template #default="scope">
            <span :class="getRatioClass(scope.row.ratio)">
              {{ formatRatio(scope.row.ratio) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          prop="target"
          label="目标值"
          width="100"
          sortable
        >
          <template #default="scope">
            {{ formatNumberWithCommas(scope.row.target) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="achievement"
          label="达成率"
          width="120"
          sortable
        >
          <template #default="scope">
            <el-progress
              :percentage="scope.row.achievement"
              :status="getProgressStatus(scope.row.achievement)"
              :stroke-width="8"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="trend"
          label="趋势"
          min-width="180"
        >
          <template #default="scope">
            <div v-if="!loading" class="mini-chart">
              <base-chart
                :option="getMiniChartOption(scope.row.trend)"
                height="30px"
                :auto-resize="true"
              />
            </div>
            <div v-else class="mini-chart-loading"></div>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
// Analytics.vue 的全部 <script setup>（含你原来的图表配置）
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
import {
  TrendCharts,
  Refresh,
  Download,
  Search,
  InfoFilled,
  DataAnalysis,
  Timer,
  User,
  Money,
  ShoppingCart,
  Platform,
  Promotion
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import BaseChart from '@/components/charts/BaseChart.vue'
import StatCard from '@/components/charts/StatCard.vue'

// 页面状态
const loading = ref(false)
const timeRange = ref('7days')
const timeRangeOptions = [
  { value: 'today', label: '今日' },
  { value: 'yesterday', label: '昨日' },
  { value: '7days', label: '近7天' },
  { value: '30days', label: '近30天' },
  { value: '90days', label: '近90天' },
  { value: 'custom', label: '自定义' }
]

// 选择的指标
const selectedMetric = ref('visits')
const metrics = [
  { value: 'visits', label: '访问量' },
  { value: 'users', label: '用户数' },
  { value: 'conversions', label: '转化率' },
  { value: 'revenue', label: '营收' }
]

// 用户分布类型
const userDistType = ref('province')

// 表格状态
const searchQuery = ref('')
const tableFilterType = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)

// 统计卡片
const statCards = [
  {
    value: 25764,
    label: '日访问量',
    icon: Platform,
    type: 'primary',
    trend: { type: 'up', value: 12.5 },
    chartData: [120, 132, 101, 134, 90, 230, 210]
  },
  {
    value: 1284,
    label: '新增用户',
    icon: User,
    type: 'success',
    trend: { type: 'up', value: 5.2 },
    chartData: [220, 182, 191, 234, 290, 330, 310]
  },
  {
    value: 6785,
    label: '订单总数',
    icon: ShoppingCart,
    type: 'warning',
    trend: { type: 'down', value: 2.8 },
    chartData: [150, 232, 201, 154, 190, 330, 410]
  },
  {
    value: 127625,
    unit: '元',
    label: '总营收',
    icon: Money,
    type: 'danger',
    trend: { type: 'up', value: 8.9 },
    chartData: [320, 332, 301, 334, 390, 330, 320]
  }
]

// 趋势数据
const generateTrendData = () => {
  const now = new Date()
  const dates = Array(30).fill(0).map((_, i) => {
    const date = new Date(now)
    date.setDate(date.getDate() - (29 - i))
    return date.toISOString().split('T')[0]
  })
  return {
    visits: dates.map(date => [date, Math.floor(Math.random() * 5000) + 20000]),
    users: dates.map(date => [date, Math.floor(Math.random() * 1000) + 800]),
    conversions: dates.map(date => [date, Math.floor(Math.random() * 20) + 10]),
    revenue: dates.map(date => [date, Math.floor(Math.random() * 50000) + 100000])
  }
}
const trendData = reactive(generateTrendData())

// 趋势图表配置
const trendChartOption = computed(() => {
  const data = trendData[selectedMetric.value]
  const yAxisFormatter = (value) => {
    if (selectedMetric.value === 'conversions') return value + '%'
    if (selectedMetric.value === 'revenue') return (value / 10000).toFixed(1) + '万'
    return value
  }
  return {
    tooltip: { trigger: 'axis', formatter: p => `${p[0].name} <br/>${p[0].seriesName}: ${p[0].value}` },
    grid: { left: 3, right: 4, bottom: 3, containLabel: true },
    xAxis: { type: 'category', boundaryGap: false, data: data.map(d => d[0]) },
    yAxis: { type: 'value', axisLabel: { formatter: yAxisFormatter } },
    series: [{
      name: metrics.find(m => m.value === selectedMetric.value).label,
      type: 'line',
      smooth: true,
      data: data.map(d => d[1]),
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: 'rgba(64, 158, 255, 0.6)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ]
        }
      },
      lineStyle: { width: 3, color: '#409EFF' },
      itemStyle: { color: '#409EFF' }
    }]
  }
})

// 用户地域分布图表配置（原样）
const userDistributionChartOption = computed(() => {
  if (userDistType.value === 'device') {
    return {
      tooltip: { trigger: 'item', formatter: '{a} <br/>{b}: {c} ({d}%)' },
      legend: { orient: 'horizontal', bottom: 0 },
      series: [{
        name: '设备分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: { borderColor: '#fff', borderWidth: 2 },
        label: { show: false, position: 'center' },
        emphasis: { label: { show: true, fontSize: '12', fontWeight: 'bold' } },
        labelLine: { show: false },
        data: [
          { value: 1048, name: '移动端' },
          { value: 735, name: '桌面端' },
          { value: 580, name: '平板' },
          { value: 484, name: '微信小程序' },
          { value: 300, name: '其他' }
        ]
      }]
    }
  } else {
    return {
      tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
      grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
      xAxis: { type: 'value', boundaryGap: [0, 0.01] },
      yAxis: {
        type: 'category',
        data: userDistType.value === 'province'
          ? ['北京', '上海', '广东', '江苏', '浙江', '四川', '湖北', '其他']
          : ['北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '其他']
      },
      series: [{
        name: userDistType.value === 'province' ? '省份分布' : '城市分布',
        type: 'bar',
        data: [18203, 23489, 29034, 10970, 16744, 9851, 7556, 45230],
        itemStyle: {
          color: function(params) {
            const colorList = [
              '#5470c6', '#91cc75', '#fac858', '#ee6666',
              '#73c0de', '#3ba272', '#fc8452', '#9a60b4'
            ]
            return colorList[params.dataIndex % colorList.length]
          }
        }
      }]
    }
  }
})

// 转化漏斗图表配置（原样）
const funnelChartOption = computed(() => {
  return {
    tooltip: { trigger: 'item', formatter: '{a} <br/>{b} : {c}%' },
    legend: { data: ['访问', '注册', '激活', '付费', '复购'], bottom: 0 },
    series: [{
      name: '转化率',
      type: 'funnel',
      left: '10%',
      top: 10,
      bottom: 40,
      width: '80%',
      min: 0,
      max: 100,
      minSize: '0%',
      maxSize: '100%',
      sort: 'descending',
      gap: 2,
      label: { show: true, position: 'inside' },
      labelLine: { length: 10, lineStyle: { width: 1, type: 'solid' } },
      itemStyle: { borderColor: '#fff', borderWidth: 1 },
      emphasis: { label: { fontSize: 14, fontWeight: 'bold' } },
      data: [
        { value: 100, name: '访问' },
        { value: 68, name: '注册' },
        { value: 42, name: '激活' },
        { value: 25, name: '付费' },
        { value: 12, name: '复购' }
      ]
    }]
  }
})

// 100 条完整表格数据
const generateTableData = () => {
  const types = [
    '访问量', '页面浏览', '新用户', '活跃用户', '订单数', '成交金额',
    '转化率', '平均停留时间', '跳出率', '复购率', '客单价', '退款金额',
    '搜索次数', '点击次数', '点赞数', '分享数', '评论数', '收藏数',
    '下载量', '上传量', '表单提交', '表单完成', '短信发送', '短信到达',
    '邮件发送', '邮件打开', '邮件点击', '推送发送', '推送点击', '推送到达',
    '支付成功', '支付失败', '支付超时', '注册成功', '注册失败', '登录次数',
    '登录失败', '密码修改', '找回密码', '绑定手机', '绑定邮箱', '绑定微信',
    '实名认证', '身份信息', '银行卡绑定', '银行卡解绑', '提现申请', '提现成功',
    '提现失败', '充值金额', '充值成功', '充值失败', '优惠券领取', '优惠券使用',
    '优惠券过期', '积分获取', '积分消耗', '积分过期', '邀请注册', '邀请成功',
    '邀请失败', '任务完成', '任务失败', '活动参与', '活动完成', '活动退出',
    '问卷填写', '问卷完成', '问卷退出', '客服咨询', '客服回复', '投诉提交',
    '投诉处理', '退款申请', '退款成功', '退款失败', '物流发货', '物流签收',
    '物流异常', '商品浏览', '商品收藏', '商品加购', '商品下单', '商品支付',
    '商品评价', '商品退货', '商品换货', '商品维修', '会员升级', '会员续费',
    '会员到期', '每日签到', '连续签到', '签到中断', '抽奖参与', '抽奖中奖'
  ]

  const data = []
  const now = new Date()
  for (let i = 0; i < 100; i++) {
    const date = new Date(now)
    date.setDate(date.getDate() - (i % 30))
    const value = Math.floor(Math.random() * 20000) + 500
    const target = Math.floor(Math.random() * 10000) + 1000
    const ratio = (Math.random() * 40) - 20
    const achievement = Math.min(Math.round((value / target) * 100), 100)
    data.push({
      date: date.toISOString().split('T')[0],
      name: types[i % types.length],
      value,
      ratio,
      target,
      achievement,
      trend: Array.from({ length: 12 }, () => Math.floor(Math.random() * 100) + 50),
      important: Math.random() > 0.7,
      anomaly: Math.random() > 0.85
    })
  }
  return data
}
const tableData = ref(generateTableData())
const filteredTableData = computed(() => {
  let result = tableData.value.filter(row => {
    if (searchQuery.value && !row.name.includes(searchQuery.value) && !row.date.includes(searchQuery.value)) return false
    if (tableFilterType.value === 'important' && !row.important) return false
    if (tableFilterType.value === 'anomaly' && !row.anomaly) return false
    return true
  })
  const start = (currentPage.value - 1) * pageSize.value
  return result.slice(start, start + pageSize.value)
})

// 工具函数
const formatNumberWithCommas = (n) => n.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
const formatRatio = (r) => `${r > 0 ? '+' : ''}${r.toFixed(2)}%`
const getRatioClass = (r) => (r > 0 ? 'ratio-up' : r < 0 ? 'ratio-down' : 'ratio-flat')
const getProgressStatus = (v) => (v >= 100 ? 'success' : v >= 80 ? '' : v >= 60 ? 'warning' : 'exception')
const getMiniChartOption = (data) => ({
  tooltip: { show: false },
  xAxis: { type: 'category', show: false, boundaryGap: false },
  yAxis: { type: 'value', show: false },
  grid: { top: 0, left: 0, right: 0, bottom: 0 },
  series: [{ data, type: 'line', smooth: true, symbol: 'none', lineStyle: { width: 2, color: '#67C23A' }, areaStyle: { color: { type: 'linear', x: 0, y: 0, x2: 0, y2: 1, colorStops: [{ offset: 0, color: 'rgba(103, 194, 58, 0.3)' }, { offset: 1, color: 'rgba(103, 194, 58, 0.1)' }] } } }]
})

// 事件
const refreshData = () => {
  loading.value = true
  setTimeout(() => {
    Object.assign(trendData, generateTrendData())
    tableData.value = generateTableData()
    loading.value = false
    ElMessage.success('数据已刷新')
  }, 1000)
}
const handleCardAction = (card) => ElMessage.info(`查看 ${card.label} 的详细数据`)
const handleChartClick = (params) => ElMessage.info(`您点击了日期: ${params.name}, 值: ${params.value}`)
const exportData = () => ElMessageBox.confirm('是否确认导出当前数据？', '导出确认').then(() => ElMessage.success('数据导出成功'))
const handleSizeChange = (val) => (pageSize.value = val)
const handleCurrentChange = (val) => (currentPage.value = val)

onMounted(() => nextTick(() => setTimeout(refreshData, 300)))
</script>

<style lang="scss" scoped>
.analytics-page {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;

  .header-left {
    h1 {
      font-size: 24px;
      font-weight: 600;
      margin: 0 0 8px 0;
      color: #303133;
    }
    .subtitle {
      font-size: 14px;
      color: #909399;
      margin: 0;
    }
  }

  .header-right {
    display: flex;
    align-items: center;
    gap: 12px;

    .time-range-select {
      width: 140px;
    }
  }
}

.stat-cards-row {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.main-chart-card {
  margin-bottom: 24px;
}

.data-analysis-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.chart-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  h3 {
    font-size: 16px;
    font-weight: 500;
    margin: 0;
    color: #303133;
  }

  .info-icon {
    font-size: 16px;
    color: #909399;
    cursor: help;
  }
}

.chart-loading-container {
  padding: 20px 0;
}

.data-table-card {
  margin-bottom: 24px;

  .table-controls {
    display: flex;
    align-items: center;
  }

  .table-pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .mini-chart {
    width: 100%;
    height: 30px;
    min-width: 120px;
  }

  .mini-chart-loading {
    width: 100%;
    height: 30px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }
}

.ratio-up {
  color: #67c23a;
}
.ratio-down {
  color: #f56c6c;
}
.ratio-flat {
  color: #909399;
}

@media screen and (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;

    .header-right {
      margin-top: 16px;
      width: 100%;
      flex-wrap: wrap;

      .time-range-select {
        width: 100%;
        margin-bottom: 8px;
      }
    }
  }

  .stat-cards-row,
  .data-analysis-row {
    grid-template-columns: 1fr;
  }
}
</style>